package Controller;

        import Dto.NewsTbEntity;
        import Dto.UserTbEntity;
        import MEx.MExAPI;
        import repository.NewsRepository;
        import repository.UserRepository;
        import repository.UserTbRepository;

        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.swing.*;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.util.Vector;

@WebServlet(name = "NewsTable")
public class UserTable extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UserTable(){
        super();
        //TODO Auto-generated constructor stub
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String a = request.getParameter("FN");
        System.out.println("a="+a);

        try {
//            NewsRepository newsRepository = new NewsRepository();
            UserTbRepository userTbRepository = new UserTbRepository();
            Vector<UserTbEntity> UsersList = userTbRepository.getUserTable();
            if(UsersList == null) {
                out.write("{\"Result\":\"FailB\"}");
                out.flush();
                out.close();
            }
            String json = "{\"UsersList\":[";

            for(UserTbEntity model:UsersList)
            {
                String[] keys = {"UserID","UserName","UserAccount","UserPwd","UserRoot"};
                Object[] objs = {model.getUserId(),model.getUserName(),model.getUserAccount(),model.getUserPwd(),model.getAdmin()};
                json += MExAPI.toJson(keys,objs);
                if(model != UsersList.lastElement())
                    json+=",";
            }

            json += "],";

            json +="\"Result\": \"Success\"}";

            out.write(json);
        }
        catch (Exception e){
            e.printStackTrace();
            out.write("{\"Result\":\"Fail\"}");
        }
        finally{
            out.flush();
            out.close();
        }

    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
